﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Media.Imaging;

namespace MedVis
{
    public partial class MainWindow : Window
    {
        private void initDialogs()
        {
            this.folderDialog = new FolderBrowserDialog();



            this.openFileDialog = new OpenFileDialog();
            // Set the file dialog to filter for graphics files.
            this.openFileDialog.Filter = "Projects (*.xml)|*.xml|" + "All files (*.*)|*.*";
            // Allow the user to select multiple images.
            this.openFileDialog.Title = "Load Project";
            this.openFileDialog.RestoreDirectory = true;



            this.saveFileDialog = new SaveFileDialog();
            // Set the file dialog to filter for graphics files.
            this.saveFileDialog.Filter = "Projects (*.xml)|*.xml|" + "All files (*.*)|*.*";
            saveFileDialog.FilterIndex = 1;
            // Allow the user to select multiple images.
            this.openFileDialog.Title = "Save Project";
            this.openFileDialog.RestoreDirectory = true;
        }

        private delegate void NoArgDelegate();
        public static void Refresh(DependencyObject obj)
        {
            obj.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Loaded,
                (NoArgDelegate)delegate { });
        }

        private void openFolder()
        {
            checkUnsaveB4Leave();
            //letzten ordner vorwaehlen, wenn nicht leer
            if (!Properties.Settings.Default.lastFolder.Equals(""))
                this.folderDialog.SelectedPath = Properties.Settings.Default.lastFolder;

            if ((int)this.folderDialog.ShowDialog() == 1)
            {
                img.Clear();
                currentImage = null;
                string foldername = this.folderDialog.SelectedPath;
                String s = "";
                try
                {
                    foreach (string f in Directory.GetFiles(foldername).OrderBy(f => f))
                    {
                        s = f.ToLower();
                        if (s.EndsWith(".png") || s.EndsWith(".jpg") || s.EndsWith(".tif"))
                            img.Add(f);
                    }
                    imgArray = img.ToArray();
                    iS.reset();
                    iS.loadImages(img);

                    //nur bildnamen in liste, ohne pfad
                    int i = 0;
                    for (int q = 0; q < imgArray.Length; q++)
                    {
                        i = imgArray[q].LastIndexOf("\\") + 1;
                        imgArray[q] = imgArray[q].Substring(i);
                    }
                    list.ItemsSource = imgArray;
                    list.SelectedIndex = 0;

                    displayImage(iS.getImage(0).path);
                    Refresh(imageDisplay);
                    currentImage = iS.getImage(0);
                    loadIsValues();
                    loadImgValues();
                    refreshCropPos();
                    progressbar.Maximum = img.Count;
                    WriteableBitmap wbmp = new WriteableBitmap(new BitmapImage(new Uri(iS.getImage(0).path)));
                    tb_heightMm.Value = wbmp.PixelHeight * 25.4 / wbmp.DpiY;
                    tb_widthMm.Value = wbmp.PixelWidth * 25.4 / wbmp.DpiX;

                    //letzten ordner speichern
                    Properties.Settings.Default.lastFolder = foldername;
                    Properties.Settings.Default.currentFilePath = "";
                    Properties.Settings.Default.Save();
                    unsaved = true;
                }
                catch (Exception e)
                {
                    Console.WriteLine("--------Ordner ist Leer!!!");
                }
            }
        }

        private void openFile()
        {
            checkUnsaveB4Leave();

            string fileName = "";
            this.openFileDialog.Filter = "Projects (*.xml)|*.xml|" + "All files (*.*)|*.*";
            if ((int)this.openFileDialog.ShowDialog() == 1)
                try
                {
                    fileName = this.openFileDialog.FileName;
                    Properties.Settings.Default.currentFilePath = fileName;
                    iS.reset();
                    iS = XmlReadWrite.readXml(fileName);
                    int i = 0;
                    img.Clear();
                    foreach (MyImageObject mio in iS.getAllImages())
                    {
                        i = mio.path.LastIndexOf("\\") + 1;
                        img.Add(mio.path.Substring(i));
                    }

                    imgArray = img.ToArray();
                    list.ItemsSource = imgArray;
                    list.SelectedIndex = 0;
                    displayImage(iS.getImage(0).path);
                    Refresh(imageDisplay);
                    currentImage = iS.getImage(0);
                    loadIsValues();
                    refreshCropPos();
                    loadImgValues();
                    progressbar.Maximum = img.Count;
                    for (int j = 0; j < list.Items.Count; j++)
                    {
                        Console.WriteLine("rota:" + iS.getImage(j).rota + " x:" + iS.getImage(j).offsetX + " y:" + iS.getImage(j).offsetY);
                    }
                }
                catch (ArgumentOutOfRangeException)
                {
                    Console.WriteLine("--------Error!!!");
                }
        }

        private void saveFile()
        {
            string fileName = "";
            this.saveFileDialog.Filter = "Projects (*.xml)|*.xml|" + "All files (*.*)|*.*";
            if ((int)this.saveFileDialog.ShowDialog() == 1)
                try
                {
                    fileName = this.saveFileDialog.FileName;
                    saveImgValues();
                    int i = fileName.LastIndexOf("\\") + 1;
                    string path = fileName.Remove(i);
                    string name = fileName.Substring(i);
                    Properties.Settings.Default.currentFilePath = fileName;
                    saveIsValues();
                    XmlReadWrite.writeXml(path, name, iS);
                    unsaved = false;
                }
                catch (ArgumentOutOfRangeException)
                {
                    Console.WriteLine("--------Error!!!");
                }
        }

        private void exportFile()
        {
            string fileName = "";
            this.saveFileDialog.Filter = "Projects (*.vm2)|*.vm2|" + "All files (*.*)|*.*";
            if ((int)this.saveFileDialog.ShowDialog() == 1)
                try
                {
                    saveImgValues();
                    saveIsValues();
                    fileName = this.saveFileDialog.FileName;
                    worker = new BackgroundWorker();
                    worker.WorkerReportsProgress = true;
                    worker.DoWork += export3DTest;
                    worker.ProgressChanged += worker_ProgressChanged;

                    worker.RunWorkerAsync(fileName);
                }
                catch (ArgumentOutOfRangeException)
                {
                    Console.WriteLine("--------Error!!!");
                }
        }
        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressbar.Value = e.ProgressPercentage;
        }

        private void save(object sender, RoutedEventArgs e)
        {
            if (iS.imageObjects.Count >= 1)
            {
                if (!Properties.Settings.Default.currentFilePath.Equals(""))
                {
                    saveIsValues();
                    saveImgValues();
                    int i = Properties.Settings.Default.currentFilePath.LastIndexOf("\\") + 1;
                    string path = Properties.Settings.Default.currentFilePath.Remove(i);
                    string name = Properties.Settings.Default.currentFilePath.Substring(i);
                    XmlReadWrite.writeXml(path, name, iS);
                    unsaved = false;
                }
                else
                {
                    saveFile();
                }
            }
        }
    }
}
